import 'package:flutter/material.dart';
import 'package:proj_sfv/domain/Video.dart';
import 'package:proj_sfv/domain/videoVo.dart';
import 'package:proj_sfv/http/requests.dart';
import 'package:proj_sfv/pages/myVideoDetailPage.dart';
import 'package:proj_sfv/store/MyArguments.dart';


class VideoSearchDetailPage extends StatefulWidget {

  VideoSearchDetailPage();

  @override
  _VideoListState createState() => _VideoListState();
}

class _VideoListState extends State<VideoSearchDetailPage> {
  List<Video> videos = [];
  bool _isAscending = true;
  MyArguments arguments;

  void _toggleSort() {
    setState(() {
      _isAscending = !_isAscending;
      videos.sort((b, a) => _isAscending ? a.likeCount.compareTo(b.likeCount) : b.likeCount.compareTo(a.likeCount));
    });
  }

  @override
  void didChangeDependencies() {
    arguments = ModalRoute.of(context).settings.arguments as MyArguments;
    searchVideoRequest(context, arguments.searchWords).then((value) {
        setState(() {
          videos = value;
          videos.sort((a, b) => b.likeCount.compareTo(a.likeCount));
        });
    });
    super.didChangeDependencies();
  }

  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('搜索结果'),
      ),
      body: Column(
        children: <Widget>[
          Padding(
            padding: EdgeInsets.all(16.0),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.end,
              children: <Widget>[
                Text('点赞数排序'),
                Switch(
                  value: _isAscending,
                  onChanged: (value) => _toggleSort(),
                ),
              ],
            ),
          ),
          Expanded(
            child: ListView.builder(
              itemCount: videos.length,
              itemBuilder: (BuildContext context, int index) {
                return ListTile(
                  onTap: () {
                    VideoVo vo = VideoVo.fromVideo(videos[index]);
                    Navigator.push(context, MaterialPageRoute(builder: (context) =>
                        MyVideoDetailPage(vo, false, arguments.token, null, () {}),));
                  },
                  leading: Image.network(videos[index].profileUrl) ?? Container(),
                  title: Text(videos[index].videoName),
                  subtitle: Text(videos[index].authorId.toString()),
                  trailing: Text('${videos[index].likeCount} 点赞'),
                );
              },
            ),
          ),
        ],
      ),
    );
  }
}
